<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>perlthrtut - Tutorial on threads in Perl - Perldoc Browser</title>
    <link rel="search" href="https://perldoc.perl.org/opensearch.xml" type="application/opensearchdescription+xml" title="Perldoc Browser">
    <link rel="canonical" href="https://perldoc.perl.org/perlthrtut">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/styles/stackoverflow-light.min.css" integrity="sha512-cG1IdFxqipi3gqLmksLtuk13C+hBa57a6zpWxMeoY3Q9O6ooFxq50DayCdm0QrDgZjMUn23z/0PMZlgft7Yp5Q==" crossorigin="anonymous" />
    <style>
      body {
        background: #f4f4f5;
        color: #020202;
      }
      .navbar-dark {
        background-image: -webkit-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: -o-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: linear-gradient(to bottom, #005f85 0, #002e49 100%);
        filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff005f85', endColorstr='#ff002e49', GradientType=0);
        background-repeat: repeat-x;
      }
      .navbar-dark .navbar-nav .nav-link,
      .navbar-dark .navbar-nav .nav-link:focus { color: #fff }
      .navbar-dark .navbar-nav .nav-link:hover { color: #ffef68 }
      #wrapperlicious {
        margin: 0 auto;
        font: 0.9em 'Helvetica Neue', Helvetica, sans-serif;
        font-weight: normal;
        line-height: 1.5em;
        margin: 0;
        padding: 0;
      }
      #wrapperlicious h1 { font-size: 1.5em }
      #wrapperlicious h2 { font-size: 1.3em }
      #wrapperlicious h3 { font-size: 1.1em }
      #wrapperlicious h4 { font-size: 0.9em }
      #wrapperlicious h1, #wrapperlicious h2, #wrapperlicious h3,
      #wrapperlicious h4, #wrapperlicious dt {
        color: #020202;
        margin-top: 1em;
        margin-bottom: 1em;
        position: relative;
        font-weight: bold;
      }
      #wrapperlicious a { color: inherit; text-decoration: underline }
      #wrapperlicious #toc { text-decoration: none }
      #wrapperlicious a:hover { color: #2a2a2a }
      #wrapperlicious a img { border: 0 }
      #wrapperlicious :not(pre) > code {
        color: inherit;
        background-color: rgba(0, 0, 0, 0.04);
        border-radius: 3px;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        padding: 0.3em;
      }
      #wrapperlicious dd {
        margin: 0;
        margin-left: 2em;
      }
      #wrapperlicious dt {
        color: #2a2a2a;
        font-weight: bold;
        margin-left: 0.9em;
      }
      #wrapperlicious p {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious li > p {
        margin-bottom: 0;
        margin-top: 0;
      }
      #wrapperlicious pre {
        border: 1px solid #c1c1c1;
        border-radius: 3px;
        font: 100% Consolas, Menlo, Monaco, monospace;
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious pre > code {
        display: block;
        background-color: #f6f6f6;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        line-height: 1.5em;
        text-align: left;
        white-space: pre;
        padding: 1em;
      }
      #wrapperlicious dl, #wrapperlicious ol, #wrapperlicious ul {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious ul {
        list-style-type: square;
      }
      #wrapperlicious ul ul {
        margin-bottom: 0px;
        margin-top: 0px;
      }
      #footer {
        font-size: 0.8em;
        padding-top: 0.5em;
        text-align: center;
      }
      #more {
        display: inline;
        font-size: 0.8em;
      }
      #perldocdiv {
        background-color: #fff;
        border: 1px solid #c1c1c1;
        border-bottom-left-radius: 5px;
        border-bottom-right-radius: 5px;
        margin-left: auto;
        margin-right: auto;
        padding: 3em;
        padding-top: 1em;
        max-width: 960px;
      }
      #moduleversion { float: right }
      #wrapperlicious .leading-notice {
        font-style: italic;
        padding-left: 1em;
        margin-top: 1em;
        margin-bottom: 1em;
      }
      #wrapperlicious .permalink {
        display: none;
        left: -0.75em;
        position: absolute;
        padding-right: 0.25em;
        text-decoration: none;
      }
      #wrapperlicious h1:hover .permalink, #wrapperlicious h2:hover .permalink,
      #wrapperlicious h3:hover .permalink, #wrapperlicious h4:hover .permalink,
      #wrapperlicious dt:hover .permalink {
        display: block;
      }
    </style>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-KVNWBNT5FB"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', 'G-KVNWBNT5FB');
      gtag('config', 'UA-50555-3');
    </script>
  </head>
  <body>
    <nav class="navbar navbar-expand-md navbar-dark bg-dark justify-content-between">
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <a class="navbar-brand" href="https://perldoc.perl.org/">Perldoc Browser</a>
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlthrtut.html#" id="dropdownlink-stable" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">5.35.0</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-stable">
          <a class="dropdown-item" href="https://perldoc.perl.org/perlthrtut">Latest</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.2/perlthrtut">5.38.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.1/perlthrtut">5.38.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0/perlthrtut">5.38.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.3/perlthrtut">5.36.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.2/perlthrtut">5.36.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.1/perlthrtut">5.36.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.0/perlthrtut">5.36.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.3/perlthrtut">5.34.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.2/perlthrtut">5.34.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.1/perlthrtut">5.34.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.0/perlthrtut">5.34.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.1/perlthrtut">5.32.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.0/perlthrtut">5.32.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.3/perlthrtut">5.30.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.2/perlthrtut">5.30.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.1/perlthrtut">5.30.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.0/perlthrtut">5.30.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.3/perlthrtut">5.28.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.2/perlthrtut">5.28.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.1/perlthrtut">5.28.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.0/perlthrtut">5.28.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.3/perlthrtut">5.26.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.2/perlthrtut">5.26.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.1/perlthrtut">5.26.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.0/perlthrtut">5.26.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.4/perlthrtut">5.24.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.3/perlthrtut">5.24.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.2/perlthrtut">5.24.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.1/perlthrtut">5.24.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.0/perlthrtut">5.24.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.4/perlthrtut">5.22.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.3/perlthrtut">5.22.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.2/perlthrtut">5.22.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.1/perlthrtut">5.22.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.0/perlthrtut">5.22.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.3/perlthrtut">5.20.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.2/perlthrtut">5.20.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.1/perlthrtut">5.20.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.0/perlthrtut">5.20.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.4/perlthrtut">5.18.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.3/perlthrtut">5.18.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.2/perlthrtut">5.18.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.1/perlthrtut">5.18.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.0/perlthrtut">5.18.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.3/perlthrtut">5.16.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.2/perlthrtut">5.16.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.1/perlthrtut">5.16.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.0/perlthrtut">5.16.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.4/perlthrtut">5.14.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.3/perlthrtut">5.14.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.2/perlthrtut">5.14.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.1/perlthrtut">5.14.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.0/perlthrtut">5.14.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.5/perlthrtut">5.12.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.4/perlthrtut">5.12.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.3/perlthrtut">5.12.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.2/perlthrtut">5.12.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.1/perlthrtut">5.12.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.0/perlthrtut">5.12.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.1/perlthrtut">5.10.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.0/perlthrtut">5.10.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.9/perlthrtut">5.8.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.8/perlthrtut">5.8.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.7/perlthrtut">5.8.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.6/perlthrtut">5.8.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.5/perlthrtut">5.8.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.4/perlthrtut">5.8.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.3/perlthrtut">5.8.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.2/perlthrtut">5.8.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.1/perlthrtut">5.8.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.0/perlthrtut">5.8.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.2/perlthrtut">5.6.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.1/perlthrtut">5.6.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.0/perlthrtut">5.6.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_04/perlthrtut">5.005_04</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_03/perlthrtut">5.005_03</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_02/perlthrtut">5.005_02</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_01/perlthrtut">5.005_01</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005/perlthrtut">5.005</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlthrtut.html#" id="dropdownlink-dev" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dev</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-dev">
          <a class="dropdown-item" href="https://perldoc.perl.org/blead/perlthrtut">blead</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.6/perlthrtut">5.39.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.5/perlthrtut">5.39.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.4/perlthrtut">5.39.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.3/perlthrtut">5.39.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.2/perlthrtut">5.39.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.1/perlthrtut">5.39.1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC2/perlthrtut">5.38.0-RC2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC1/perlthrtut">5.38.0-RC1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.11/perlthrtut">5.37.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.10/perlthrtut">5.37.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.9/perlthrtut">5.37.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.8/perlthrtut">5.37.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.7/perlthrtut">5.37.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.6/perlthrtut">5.37.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.5/perlthrtut">5.37.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.4/perlthrtut">5.37.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.3/perlthrtut">5.37.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.2/perlthrtut">5.37.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.1/perlthrtut">5.37.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.0/perlthrtut">5.37.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.11/perlthrtut">5.35.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.10/perlthrtut">5.35.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.9/perlthrtut">5.35.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.8/perlthrtut">5.35.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.7/perlthrtut">5.35.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.6/perlthrtut">5.35.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.5/perlthrtut">5.35.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.4/perlthrtut">5.35.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.3/perlthrtut">5.35.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.2/perlthrtut">5.35.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.1/perlthrtut">5.35.1</a>
          <a class="dropdown-item active" href="perlthrtut.html">5.35.0</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlthrtut.html#" id="dropdownlink-nav" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Documentation</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-nav">
          <a class="dropdown-item" href="perl.html">Perl</a>
          <a class="dropdown-item" href="perlintro.html">Intro</a>
          <a class="dropdown-item" href="perl.html#Tutorials">Tutorials</a>
          <a class="dropdown-item" href="perlfaq.html">FAQs</a>
          <a class="dropdown-item" href="perl.html#Reference-Manual">Reference</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlop.html">Operators</a>
          <a class="dropdown-item" href="functions.html">Functions</a>
          <a class="dropdown-item" href="variables.html">Variables</a>
          <a class="dropdown-item" href="modules.html">Modules</a>
          <a class="dropdown-item" href="perlutil.html">Utilities</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlcommunity.html">Community</a>
          <a class="dropdown-item" href="perlhist.html">History</a>
        </div>
      </li>
    </ul>
    <ul class="navbar-nav">
      <script>
        function set_expand (expand) {
          var perldocdiv = document.getElementById('perldocdiv');
          var width = window.getComputedStyle(perldocdiv).getPropertyValue('max-width');
          var expanded = (width == '' || width == 'none') ? true : false;
          if (expand === null) {
            expand = !expanded;
          }
          if ((expand && !expanded) || (!expand && expanded)) {
            perldocdiv.style.setProperty('max-width', expand ? 'none' : '960px');
            var button_classlist = document.getElementById('content-expand-button').classList;
            if (expand) {
              button_classlist.add('btn-light');
              button_classlist.remove('btn-outline-light');
            } else {
              button_classlist.add('btn-outline-light');
              button_classlist.remove('btn-light');
            }
          }
          return expand;
        }
        function toggle_expand () {
          var expand = set_expand(null);
          document.cookie = 'perldoc_expand=' + (expand ? 1 : 0) + '; path=/; expires=Tue, 19 Jan 2038 03:14:07 UTC';
        }
        function read_expand () {
          return document.cookie.split(';').some(function (item) { return item.indexOf('perldoc_expand=1') >= 0 });
        }
        if (document.readyState === 'loading') {
          document.addEventListener('DOMContentLoaded', function () {
            if (read_expand()) {
              set_expand(true);
            }
          });
        } else if (read_expand()) {
          set_expand(true);
        }
      </script>
      <button id="content-expand-button" type="button" class="btn btn-outline-light d-none d-lg-inline-block mr-2" onclick="toggle_expand()">Expand</button>
    <ul>
    <form class="form-inline" method="get" action="https://perldoc.perl.org/5.35.0/search">
      <input class="form-control mr-3" type="search" name="q" placeholder="Search" aria-label="Search">
    </form>
  </div>
</nav>

    <div id="wrapperlicious" class="container-fluid">
      <div id="perldocdiv">
        <div id="links">
          <a href="perlthrtut.html">perlthrtut</a>
          <div id="more">
            (<a href="perlthrtut.txt">source</a>,
            <a href="https://metacpan.org/pod/perlthrtut">CPAN</a>)
          </div>
        </div>
        <div class="leading-notice">
          You are viewing the version of this documentation from Perl 5.35.0.
            This is a development version of Perl.
        </div>
        <h1><a id="toc">CONTENTS</a></h1>
                  <ul>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#NAME">NAME</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#DESCRIPTION">DESCRIPTION</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#What-Is-A-Thread-Anyway?">What Is A Thread Anyway?</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Threaded-Program-Models">Threaded Program Models</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Boss/Worker">Boss/Worker</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Work-Crew">Work Crew</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Pipeline">Pipeline</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#What-kind-of-threads-are-Perl-threads?">What kind of threads are Perl threads?</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Thread-Safe-Modules">Thread-Safe Modules</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Thread-Basics">Thread Basics</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Basic-Thread-Support">Basic Thread Support</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#A-Note-about-the-Examples">A Note about the Examples</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Creating-Threads">Creating Threads</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Waiting-For-A-Thread-To-Exit">Waiting For A Thread To Exit</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Ignoring-A-Thread">Ignoring A Thread</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Process-and-Thread-Termination">Process and Thread Termination</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Threads-And-Data">Threads And Data</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Shared-And-Unshared-Data">Shared And Unshared Data</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Thread-Pitfalls:-Races">Thread Pitfalls: Races</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Synchronization-and-control">Synchronization and control</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Controlling-access:-lock()">Controlling access: lock()</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#A-Thread-Pitfall:-Deadlocks">A Thread Pitfall: Deadlocks</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Queues:-Passing-Data-Around">Queues: Passing Data Around</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Semaphores:-Synchronizing-Data-Access">Semaphores: Synchronizing Data Access</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Basic-semaphores">Basic semaphores</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Advanced-Semaphores">Advanced Semaphores</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Waiting-for-a-Condition">Waiting for a Condition</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Giving-up-control">Giving up control</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#General-Thread-Utility-Routines">General Thread Utility Routines</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#What-Thread-Am-I-In?">What Thread Am I In?</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Thread-IDs">Thread IDs</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Are-These-Threads-The-Same?">Are These Threads The Same?</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#What-Threads-Are-Running?">What Threads Are Running?</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#A-Complete-Example">A Complete Example</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Different-implementations-of-threads">Different implementations of threads</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Performance-considerations">Performance considerations</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Process-scope-Changes">Process-scope Changes</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Thread-Safety-of-System-Libraries">Thread-Safety of System Libraries</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Conclusion">Conclusion</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#SEE-ALSO">SEE ALSO</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Bibliography">Bibliography</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Introductory-Texts">Introductory Texts</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#OS-Related-References">OS-Related References</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Other-References">Other References</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Acknowledgements">Acknowledgements</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#AUTHOR">AUTHOR</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlthrtut.html#Copyrights">Copyrights</a>
              </li>
          </ul>

      <h1 id="NAME"><a class="permalink" href="perlthrtut.html#NAME">#</a>NAME</h1>

<p>perlthrtut - Tutorial on threads in Perl</p>

<h1 id="DESCRIPTION"><a class="permalink" href="perlthrtut.html#DESCRIPTION">#</a>DESCRIPTION</h1>

<p>This tutorial describes the use of Perl interpreter threads (sometimes referred to as <i>ithreads</i>). In this model, each thread runs in its own Perl interpreter, and any data sharing between threads must be explicit. The user-level interface for <i>ithreads</i> uses the <a href="threads.html">threads</a> class.</p>

<p><b>NOTE</b>: There was another older Perl threading flavor called the 5.005 model that used the <a href="threads.html">threads</a> class. This old model was known to have problems, is deprecated, and was removed for release 5.10. You are strongly encouraged to migrate any existing 5.005 threads code to the new model as soon as possible.</p>

<p>You can see which (or neither) threading flavour you have by running <code>perl -V</code> and looking at the <code>Platform</code> section. If you have <code>useithreads=define</code> you have ithreads, if you have <code>use5005threads=define</code> you have 5.005 threads. If you have neither, you don&#39;t have any thread support built in. If you have both, you are in trouble.</p>

<p>The <a href="threads.html">threads</a> and <a href="./threads::shared.html">threads::shared</a> modules are included in the core Perl distribution. Additionally, they are maintained as a separate modules on CPAN, so you can check there for any updates.</p>

<h1 id="What-Is-A-Thread-Anyway?"><a class="permalink" href="perlthrtut.html#What-Is-A-Thread-Anyway?">#</a><a id="What"></a><a id="What-Is-A-Thread-Anyway"></a>What Is A Thread Anyway?</h1>

<p>A thread is a flow of control through a program with a single execution point.</p>

<p>Sounds an awful lot like a process, doesn&#39;t it? Well, it should. Threads are one of the pieces of a process. Every process has at least one thread and, up until now, every process running Perl had only one thread. With 5.8, though, you can create extra threads. We&#39;re going to show you how, when, and why.</p>

<h1 id="Threaded-Program-Models"><a class="permalink" href="perlthrtut.html#Threaded-Program-Models">#</a><a id="Threaded"></a>Threaded Program Models</h1>

<p>There are three basic ways that you can structure a threaded program. Which model you choose depends on what you need your program to do. For many non-trivial threaded programs, you&#39;ll need to choose different models for different pieces of your program.</p>

<h2 id="Boss/Worker"><a class="permalink" href="perlthrtut.html#Boss/Worker">#</a><a id="Boss"></a><a id="Boss-Worker"></a>Boss/Worker</h2>

<p>The boss/worker model usually has one <i>boss</i> thread and one or more <i>worker</i> threads. The boss thread gathers or generates tasks that need to be done, then parcels those tasks out to the appropriate worker thread.</p>

<p>This model is common in GUI and server programs, where a main thread waits for some event and then passes that event to the appropriate worker threads for processing. Once the event has been passed on, the boss thread goes back to waiting for another event.</p>

<p>The boss thread does relatively little work. While tasks aren&#39;t necessarily performed faster than with any other method, it tends to have the best user-response times.</p>

<h2 id="Work-Crew"><a class="permalink" href="perlthrtut.html#Work-Crew">#</a><a id="Work"></a>Work Crew</h2>

<p>In the work crew model, several threads are created that do essentially the same thing to different pieces of data. It closely mirrors classical parallel processing and vector processors, where a large array of processors do the exact same thing to many pieces of data.</p>

<p>This model is particularly useful if the system running the program will distribute multiple threads across different processors. It can also be useful in ray tracing or rendering engines, where the individual threads can pass on interim results to give the user visual feedback.</p>

<h2 id="Pipeline"><a class="permalink" href="perlthrtut.html#Pipeline">#</a>Pipeline</h2>

<p>The pipeline model divides up a task into a series of steps, and passes the results of one step on to the thread processing the next. Each thread does one thing to each piece of data and passes the results to the next thread in line.</p>

<p>This model makes the most sense if you have multiple processors so two or more threads will be executing in parallel, though it can often make sense in other contexts as well. It tends to keep the individual tasks small and simple, as well as allowing some parts of the pipeline to block (on I/O or system calls, for example) while other parts keep going. If you&#39;re running different parts of the pipeline on different processors you may also take advantage of the caches on each processor.</p>

<p>This model is also handy for a form of recursive programming where, rather than having a subroutine call itself, it instead creates another thread. Prime and Fibonacci generators both map well to this form of the pipeline model. (A version of a prime number generator is presented later on.)</p>

<h1 id="What-kind-of-threads-are-Perl-threads?"><a class="permalink" href="perlthrtut.html#What-kind-of-threads-are-Perl-threads?">#</a><a id="What1"></a><a id="What-kind-of-threads-are-Perl-threads"></a>What kind of threads are Perl threads?</h1>

<p>If you have experience with other thread implementations, you might find that things aren&#39;t quite what you expect. It&#39;s very important to remember when dealing with Perl threads that <i>Perl Threads Are Not X Threads</i> for all values of X. They aren&#39;t POSIX threads, or DecThreads, or Java&#39;s Green threads, or Win32 threads. There are similarities, and the broad concepts are the same, but if you start looking for implementation details you&#39;re going to be either disappointed or confused. Possibly both.</p>

<p>This is not to say that Perl threads are completely different from everything that&#39;s ever come before. They&#39;re not. Perl&#39;s threading model owes a lot to other thread models, especially POSIX. Just as Perl is not C, though, Perl threads are not POSIX threads. So if you find yourself looking for mutexes, or thread priorities, it&#39;s time to step back a bit and think about what you want to do and how Perl can do it.</p>

<p>However, it is important to remember that Perl threads cannot magically do things unless your operating system&#39;s threads allow it. So if your system blocks the entire process on <code>sleep()</code>, Perl usually will, as well.</p>

<p><b>Perl Threads Are Different.</b></p>

<h1 id="Thread-Safe-Modules"><a class="permalink" href="perlthrtut.html#Thread-Safe-Modules">#</a><a id="Thread"></a>Thread-Safe Modules</h1>

<p>The addition of threads has changed Perl&#39;s internals substantially. There are implications for people who write modules with XS code or external libraries. However, since Perl data is not shared among threads by default, Perl modules stand a high chance of being thread-safe or can be made thread-safe easily. Modules that are not tagged as thread-safe should be tested or code reviewed before being used in production code.</p>

<p>Not all modules that you might use are thread-safe, and you should always assume a module is unsafe unless the documentation says otherwise. This includes modules that are distributed as part of the core. Threads are a relatively new feature, and even some of the standard modules aren&#39;t thread-safe.</p>

<p>Even if a module is thread-safe, it doesn&#39;t mean that the module is optimized to work well with threads. A module could possibly be rewritten to utilize the new features in threaded Perl to increase performance in a threaded environment.</p>

<p>If you&#39;re using a module that&#39;s not thread-safe for some reason, you can protect yourself by using it from one, and only one thread at all. If you need multiple threads to access such a module, you can use semaphores and lots of programming discipline to control access to it. Semaphores are covered in <a href="perlthrtut.html#Basic-semaphores">&quot;Basic semaphores&quot;</a>.</p>

<p>See also <a href="perlthrtut.html#Thread-Safety-of-System-Libraries">&quot;Thread-Safety of System Libraries&quot;</a>.</p>

<h1 id="Thread-Basics"><a class="permalink" href="perlthrtut.html#Thread-Basics">#</a><a id="Thread1"></a>Thread Basics</h1>

<p>The <a href="threads.html">threads</a> module provides the basic functions you need to write threaded programs. In the following sections, we&#39;ll cover the basics, showing you what you need to do to create a threaded program. After that, we&#39;ll go over some of the features of the <a href="threads.html">threads</a> module that make threaded programming easier.</p>

<h2 id="Basic-Thread-Support"><a class="permalink" href="perlthrtut.html#Basic-Thread-Support">#</a><a id="Basic"></a>Basic Thread Support</h2>

<p>Thread support is a Perl compile-time option. It&#39;s something that&#39;s turned on or off when Perl is built at your site, rather than when your programs are compiled. If your Perl wasn&#39;t compiled with thread support enabled, then any attempt to use threads will fail.</p>

<p>Your programs can use the Config module to check whether threads are enabled. If your program can&#39;t run without them, you can say something like:</p>

<pre><code>use Config;
$Config{useithreads} or
    die(&#39;Recompile Perl with threads to run this program.&#39;);</code></pre>

<p>A possibly-threaded program using a possibly-threaded module might have code like this:</p>

<pre><code>use Config;
use MyMod;

BEGIN {
    if ($Config{useithreads}) {
        # We have threads
        require MyMod_threaded;
        import MyMod_threaded;
    } else {
        require MyMod_unthreaded;
        import MyMod_unthreaded;
    }
}</code></pre>

<p>Since code that runs both with and without threads is usually pretty messy, it&#39;s best to isolate the thread-specific code in its own module. In our example above, that&#39;s what <code>MyMod_threaded</code> is, and it&#39;s only imported if we&#39;re running on a threaded Perl.</p>

<h2 id="A-Note-about-the-Examples"><a class="permalink" href="perlthrtut.html#A-Note-about-the-Examples">#</a><a id="A"></a>A Note about the Examples</h2>

<p>In a real situation, care should be taken that all threads are finished executing before the program exits. That care has <b>not</b> been taken in these examples in the interest of simplicity. Running these examples <i>as is</i> will produce error messages, usually caused by the fact that there are still threads running when the program exits. You should not be alarmed by this.</p>

<h2 id="Creating-Threads"><a class="permalink" href="perlthrtut.html#Creating-Threads">#</a><a id="Creating"></a>Creating Threads</h2>

<p>The <a href="threads.html">threads</a> module provides the tools you need to create new threads. Like any other module, you need to tell Perl that you want to use it; <code>use threads;</code> imports all the pieces you need to create basic threads.</p>

<p>The simplest, most straightforward way to create a thread is with <code>create()</code>:</p>

<pre><code>use threads;

my $thr = threads-&gt;create(\&amp;sub1);

sub sub1 {
    print(&quot;In the thread\n&quot;);
}</code></pre>

<p>The <code>create()</code> method takes a reference to a subroutine and creates a new thread that starts executing in the referenced subroutine. Control then passes both to the subroutine and the caller.</p>

<p>If you need to, your program can pass parameters to the subroutine as part of the thread startup. Just include the list of parameters as part of the <code>threads-&gt;create()</code> call, like this:</p>

<pre><code>use threads;

my $Param3 = &#39;foo&#39;;
my $thr1 = threads-&gt;create(\&amp;sub1, &#39;Param 1&#39;, &#39;Param 2&#39;, $Param3);
my @ParamList = (42, &#39;Hello&#39;, 3.14);
my $thr2 = threads-&gt;create(\&amp;sub1, @ParamList);
my $thr3 = threads-&gt;create(\&amp;sub1, qw(Param1 Param2 Param3));

sub sub1 {
    my @InboundParameters = @_;
    print(&quot;In the thread\n&quot;);
    print(&#39;Got parameters &gt;&#39;, join(&#39;&lt;&gt;&#39;,@InboundParameters), &quot;&lt;\n&quot;);
}</code></pre>

<p>The last example illustrates another feature of threads. You can spawn off several threads using the same subroutine. Each thread executes the same subroutine, but in a separate thread with a separate environment and potentially separate arguments.</p>

<p><code>new()</code> is a synonym for <code>create()</code>.</p>

<h2 id="Waiting-For-A-Thread-To-Exit"><a class="permalink" href="perlthrtut.html#Waiting-For-A-Thread-To-Exit">#</a><a id="Waiting"></a>Waiting For A Thread To Exit</h2>

<p>Since threads are also subroutines, they can return values. To wait for a thread to exit and extract any values it might return, you can use the <code>join()</code> method:</p>

<pre><code>use threads;

my ($thr) = threads-&gt;create(\&amp;sub1);

my @ReturnData = $thr-&gt;join();
print(&#39;Thread returned &#39;, join(&#39;, &#39;, @ReturnData), &quot;\n&quot;);

sub sub1 { return (&#39;Fifty-six&#39;, &#39;foo&#39;, 2); }</code></pre>

<p>In the example above, the <code>join()</code> method returns as soon as the thread ends. In addition to waiting for a thread to finish and gathering up any values that the thread might have returned, <code>join()</code> also performs any OS cleanup necessary for the thread. That cleanup might be important, especially for long-running programs that spawn lots of threads. If you don&#39;t want the return values and don&#39;t want to wait for the thread to finish, you should call the <code>detach()</code> method instead, as described next.</p>

<p>NOTE: In the example above, the thread returns a list, thus necessitating that the thread creation call be made in list context (i.e., <code>my ($thr)</code>). See <a href="threads.html#%24thr-%3Ejoin%28%29">&quot;$thr-&gt;join()&quot; in threads</a> and <a href="threads.html#THREAD-CONTEXT">&quot;THREAD CONTEXT&quot; in threads</a> for more details on thread context and return values.</p>

<h2 id="Ignoring-A-Thread"><a class="permalink" href="perlthrtut.html#Ignoring-A-Thread">#</a><a id="Ignoring"></a>Ignoring A Thread</h2>

<p><code>join()</code> does three things: it waits for a thread to exit, cleans up after it, and returns any data the thread may have produced. But what if you&#39;re not interested in the thread&#39;s return values, and you don&#39;t really care when the thread finishes? All you want is for the thread to get cleaned up after when it&#39;s done.</p>

<p>In this case, you use the <code>detach()</code> method. Once a thread is detached, it&#39;ll run until it&#39;s finished; then Perl will clean up after it automatically.</p>

<pre><code>use threads;

my $thr = threads-&gt;create(\&amp;sub1);   # Spawn the thread

$thr-&gt;detach();   # Now we officially don&#39;t care any more

sleep(15);        # Let thread run for awhile

sub sub1 {
    my $count = 0;
    while (1) {
        $count++;
        print(&quot;\$count is $count\n&quot;);
        sleep(1);
    }
}</code></pre>

<p>Once a thread is detached, it may not be joined, and any return data that it might have produced (if it was done and waiting for a join) is lost.</p>

<p><code>detach()</code> can also be called as a class method to allow a thread to detach itself:</p>

<pre><code>use threads;

my $thr = threads-&gt;create(\&amp;sub1);

sub sub1 {
    threads-&gt;detach();
    # Do more work
}</code></pre>

<h2 id="Process-and-Thread-Termination"><a class="permalink" href="perlthrtut.html#Process-and-Thread-Termination">#</a><a id="Process"></a>Process and Thread Termination</h2>

<p>With threads one must be careful to make sure they all have a chance to run to completion, assuming that is what you want.</p>

<p>An action that terminates a process will terminate <i>all</i> running threads. die() and exit() have this property, and perl does an exit when the main thread exits, perhaps implicitly by falling off the end of your code, even if that&#39;s not what you want.</p>

<p>As an example of this case, this code prints the message &quot;Perl exited with active threads: 2 running and unjoined&quot;:</p>

<pre><code>use threads;
my $thr1 = threads-&gt;new(\&amp;thrsub, &quot;test1&quot;);
my $thr2 = threads-&gt;new(\&amp;thrsub, &quot;test2&quot;);
sub thrsub {
   my ($message) = @_;
   sleep 1;
   print &quot;thread $message\n&quot;;
}</code></pre>

<p>But when the following lines are added at the end:</p>

<pre><code>$thr1-&gt;join();
$thr2-&gt;join();</code></pre>

<p>it prints two lines of output, a perhaps more useful outcome.</p>

<h1 id="Threads-And-Data"><a class="permalink" href="perlthrtut.html#Threads-And-Data">#</a><a id="Threads"></a>Threads And Data</h1>

<p>Now that we&#39;ve covered the basics of threads, it&#39;s time for our next topic: Data. Threading introduces a couple of complications to data access that non-threaded programs never need to worry about.</p>

<h2 id="Shared-And-Unshared-Data"><a class="permalink" href="perlthrtut.html#Shared-And-Unshared-Data">#</a><a id="Shared"></a>Shared And Unshared Data</h2>

<p>The biggest difference between Perl <i>ithreads</i> and the old 5.005 style threading, or for that matter, to most other threading systems out there, is that by default, no data is shared. When a new Perl thread is created, all the data associated with the current thread is copied to the new thread, and is subsequently private to that new thread! This is similar in feel to what happens when a Unix process forks, except that in this case, the data is just copied to a different part of memory within the same process rather than a real fork taking place.</p>

<p>To make use of threading, however, one usually wants the threads to share at least some data between themselves. This is done with the <a href="./threads::shared.html">threads::shared</a> module and the <code>:shared</code> attribute:</p>

<pre><code>use threads;
use threads::shared;

my $foo :shared = 1;
my $bar = 1;
threads-&gt;create(sub { $foo++; $bar++; })-&gt;join();

print(&quot;$foo\n&quot;);  # Prints 2 since $foo is shared
print(&quot;$bar\n&quot;);  # Prints 1 since $bar is not shared</code></pre>

<p>In the case of a shared array, all the array&#39;s elements are shared, and for a shared hash, all the keys and values are shared. This places restrictions on what may be assigned to shared array and hash elements: only simple values or references to shared variables are allowed - this is so that a private variable can&#39;t accidentally become shared. A bad assignment will cause the thread to die. For example:</p>

<pre><code>use threads;
use threads::shared;

my $var          = 1;
my $svar :shared = 2;
my %hash :shared;

... create some threads ...

$hash{a} = 1;       # All threads see exists($hash{a})
                    # and $hash{a} == 1
$hash{a} = $var;    # okay - copy-by-value: same effect as previous
$hash{a} = $svar;   # okay - copy-by-value: same effect as previous
$hash{a} = \$svar;  # okay - a reference to a shared variable
$hash{a} = \$var;   # This will die
delete($hash{a});   # okay - all threads will see !exists($hash{a})</code></pre>

<p>Note that a shared variable guarantees that if two or more threads try to modify it at the same time, the internal state of the variable will not become corrupted. However, there are no guarantees beyond this, as explained in the next section.</p>

<h2 id="Thread-Pitfalls:-Races"><a class="permalink" href="perlthrtut.html#Thread-Pitfalls:-Races">#</a><a id="Thread2"></a>Thread Pitfalls: Races</h2>

<p>While threads bring a new set of useful tools, they also bring a number of pitfalls. One pitfall is the race condition:</p>

<pre><code>use threads;
use threads::shared;

my $x :shared = 1;
my $thr1 = threads-&gt;create(\&amp;sub1);
my $thr2 = threads-&gt;create(\&amp;sub2);

$thr1-&gt;join();
$thr2-&gt;join();
print(&quot;$x\n&quot;);

sub sub1 { my $foo = $x; $x = $foo + 1; }
sub sub2 { my $bar = $x; $x = $bar + 1; }</code></pre>

<p>What do you think <code>$x</code> will be? The answer, unfortunately, is <i>it depends</i>. Both <code>sub1()</code> and <code>sub2()</code> access the global variable <code>$x</code>, once to read and once to write. Depending on factors ranging from your thread implementation&#39;s scheduling algorithm to the phase of the moon, <code>$x</code> can be 2 or 3.</p>

<p>Race conditions are caused by unsynchronized access to shared data. Without explicit synchronization, there&#39;s no way to be sure that nothing has happened to the shared data between the time you access it and the time you update it. Even this simple code fragment has the possibility of error:</p>

<pre><code>use threads;
my $x :shared = 2;
my $y :shared;
my $z :shared;
my $thr1 = threads-&gt;create(sub { $y = $x; $x = $y + 1; });
my $thr2 = threads-&gt;create(sub { $z = $x; $x = $z + 1; });
$thr1-&gt;join();
$thr2-&gt;join();</code></pre>

<p>Two threads both access <code>$x</code>. Each thread can potentially be interrupted at any point, or be executed in any order. At the end, <code>$x</code> could be 3 or 4, and both <code>$y</code> and <code>$z</code> could be 2 or 3.</p>

<p>Even <code>$x += 5</code> or <code>$x++</code> are not guaranteed to be atomic.</p>

<p>Whenever your program accesses data or resources that can be accessed by other threads, you must take steps to coordinate access or risk data inconsistency and race conditions. Note that Perl will protect its internals from your race conditions, but it won&#39;t protect you from you.</p>

<h1 id="Synchronization-and-control"><a class="permalink" href="perlthrtut.html#Synchronization-and-control">#</a><a id="Synchronization"></a>Synchronization and control</h1>

<p>Perl provides a number of mechanisms to coordinate the interactions between themselves and their data, to avoid race conditions and the like. Some of these are designed to resemble the common techniques used in thread libraries such as <code>pthreads</code>; others are Perl-specific. Often, the standard techniques are clumsy and difficult to get right (such as condition waits). Where possible, it is usually easier to use Perlish techniques such as queues, which remove some of the hard work involved.</p>

<h2 id="Controlling-access:-lock()"><a class="permalink" href="perlthrtut.html#Controlling-access:-lock()">#</a><a id="Controlling"></a><a id="Controlling-access:-lock"></a>Controlling access: lock()</h2>

<p>The <code>lock()</code> function takes a shared variable and puts a lock on it. No other thread may lock the variable until the variable is unlocked by the thread holding the lock. Unlocking happens automatically when the locking thread exits the block that contains the call to the <code>lock()</code> function. Using <code>lock()</code> is straightforward: This example has several threads doing some calculations in parallel, and occasionally updating a running total:</p>

<pre><code>use threads;
use threads::shared;

my $total :shared = 0;

sub calc {
    while (1) {
        my $result;
        # (... do some calculations and set $result ...)
        {
            lock($total);  # Block until we obtain the lock
            $total += $result;
        } # Lock implicitly released at end of scope
        last if $result == 0;
    }
}

my $thr1 = threads-&gt;create(\&amp;calc);
my $thr2 = threads-&gt;create(\&amp;calc);
my $thr3 = threads-&gt;create(\&amp;calc);
$thr1-&gt;join();
$thr2-&gt;join();
$thr3-&gt;join();
print(&quot;total=$total\n&quot;);</code></pre>

<p><code>lock()</code> blocks the thread until the variable being locked is available. When <code>lock()</code> returns, your thread can be sure that no other thread can lock that variable until the block containing the lock exits.</p>

<p>It&#39;s important to note that locks don&#39;t prevent access to the variable in question, only lock attempts. This is in keeping with Perl&#39;s longstanding tradition of courteous programming, and the advisory file locking that <code>flock()</code> gives you.</p>

<p>You may lock arrays and hashes as well as scalars. Locking an array, though, will not block subsequent locks on array elements, just lock attempts on the array itself.</p>

<p>Locks are recursive, which means it&#39;s okay for a thread to lock a variable more than once. The lock will last until the outermost <code>lock()</code> on the variable goes out of scope. For example:</p>

<pre><code>my $x :shared;
doit();

sub doit {
    {
        {
            lock($x); # Wait for lock
            lock($x); # NOOP - we already have the lock
            {
                lock($x); # NOOP
                {
                    lock($x); # NOOP
                    lockit_some_more();
                }
            }
        } # *** Implicit unlock here ***
    }
}

sub lockit_some_more {
    lock($x); # NOOP
} # Nothing happens here</code></pre>

<p>Note that there is no <code>unlock()</code> function - the only way to unlock a variable is to allow it to go out of scope.</p>

<p>A lock can either be used to guard the data contained within the variable being locked, or it can be used to guard something else, like a section of code. In this latter case, the variable in question does not hold any useful data, and exists only for the purpose of being locked. In this respect, the variable behaves like the mutexes and basic semaphores of traditional thread libraries.</p>

<h2 id="A-Thread-Pitfall:-Deadlocks"><a class="permalink" href="perlthrtut.html#A-Thread-Pitfall:-Deadlocks">#</a><a id="A1"></a>A Thread Pitfall: Deadlocks</h2>

<p>Locks are a handy tool to synchronize access to data, and using them properly is the key to safe shared data. Unfortunately, locks aren&#39;t without their dangers, especially when multiple locks are involved. Consider the following code:</p>

<pre><code>use threads;

my $x :shared = 4;
my $y :shared = &#39;foo&#39;;
my $thr1 = threads-&gt;create(sub {
    lock($x);
    sleep(20);
    lock($y);
});
my $thr2 = threads-&gt;create(sub {
    lock($y);
    sleep(20);
    lock($x);
});</code></pre>

<p>This program will probably hang until you kill it. The only way it won&#39;t hang is if one of the two threads acquires both locks first. A guaranteed-to-hang version is more complicated, but the principle is the same.</p>

<p>The first thread will grab a lock on <code>$x</code>, then, after a pause during which the second thread has probably had time to do some work, try to grab a lock on <code>$y</code>. Meanwhile, the second thread grabs a lock on <code>$y</code>, then later tries to grab a lock on <code>$x</code>. The second lock attempt for both threads will block, each waiting for the other to release its lock.</p>

<p>This condition is called a deadlock, and it occurs whenever two or more threads are trying to get locks on resources that the others own. Each thread will block, waiting for the other to release a lock on a resource. That never happens, though, since the thread with the resource is itself waiting for a lock to be released.</p>

<p>There are a number of ways to handle this sort of problem. The best way is to always have all threads acquire locks in the exact same order. If, for example, you lock variables <code>$x</code>, <code>$y</code>, and <code>$z</code>, always lock <code>$x</code> before <code>$y</code>, and <code>$y</code> before <code>$z</code>. It&#39;s also best to hold on to locks for as short a period of time to minimize the risks of deadlock.</p>

<p>The other synchronization primitives described below can suffer from similar problems.</p>

<h2 id="Queues:-Passing-Data-Around"><a class="permalink" href="perlthrtut.html#Queues:-Passing-Data-Around">#</a><a id="Queues"></a>Queues: Passing Data Around</h2>

<p>A queue is a special thread-safe object that lets you put data in one end and take it out the other without having to worry about synchronization issues. They&#39;re pretty straightforward, and look like this:</p>

<pre><code>use threads;
use Thread::Queue;

my $DataQueue = Thread::Queue-&gt;new();
my $thr = threads-&gt;create(sub {
    while (my $DataElement = $DataQueue-&gt;dequeue()) {
        print(&quot;Popped $DataElement off the queue\n&quot;);
    }
});

$DataQueue-&gt;enqueue(12);
$DataQueue-&gt;enqueue(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;);
sleep(10);
$DataQueue-&gt;enqueue(undef);
$thr-&gt;join();</code></pre>

<p>You create the queue with <code>Thread::Queue-&gt;new()</code>. Then you can add lists of scalars onto the end with <code>enqueue()</code>, and pop scalars off the front of it with <code>dequeue()</code>. A queue has no fixed size, and can grow as needed to hold everything pushed on to it.</p>

<p>If a queue is empty, <code>dequeue()</code> blocks until another thread enqueues something. This makes queues ideal for event loops and other communications between threads.</p>

<h2 id="Semaphores:-Synchronizing-Data-Access"><a class="permalink" href="perlthrtut.html#Semaphores:-Synchronizing-Data-Access">#</a><a id="Semaphores"></a>Semaphores: Synchronizing Data Access</h2>

<p>Semaphores are a kind of generic locking mechanism. In their most basic form, they behave very much like lockable scalars, except that they can&#39;t hold data, and that they must be explicitly unlocked. In their advanced form, they act like a kind of counter, and can allow multiple threads to have the <i>lock</i> at any one time.</p>

<h2 id="Basic-semaphores"><a class="permalink" href="perlthrtut.html#Basic-semaphores">#</a><a id="Basic1"></a>Basic semaphores</h2>

<p>Semaphores have two methods, <code>down()</code> and <code>up()</code>: <code>down()</code> decrements the resource count, while <code>up()</code> increments it. Calls to <code>down()</code> will block if the semaphore&#39;s current count would decrement below zero. This program gives a quick demonstration:</p>

<pre><code>use threads;
use Thread::Semaphore;

my $semaphore = Thread::Semaphore-&gt;new();
my $GlobalVariable :shared = 0;

$thr1 = threads-&gt;create(\&amp;sample_sub, 1);
$thr2 = threads-&gt;create(\&amp;sample_sub, 2);
$thr3 = threads-&gt;create(\&amp;sample_sub, 3);

sub sample_sub {
    my $SubNumber = shift(@_);
    my $TryCount = 10;
    my $LocalCopy;
    sleep(1);
    while ($TryCount--) {
        $semaphore-&gt;down();
        $LocalCopy = $GlobalVariable;
        print(&quot;$TryCount tries left for sub $SubNumber &quot;
             .&quot;(\$GlobalVariable is $GlobalVariable)\n&quot;);
        sleep(2);
        $LocalCopy++;
        $GlobalVariable = $LocalCopy;
        $semaphore-&gt;up();
    }
}

$thr1-&gt;join();
$thr2-&gt;join();
$thr3-&gt;join();</code></pre>

<p>The three invocations of the subroutine all operate in sync. The semaphore, though, makes sure that only one thread is accessing the global variable at once.</p>

<h2 id="Advanced-Semaphores"><a class="permalink" href="perlthrtut.html#Advanced-Semaphores">#</a><a id="Advanced"></a>Advanced Semaphores</h2>

<p>By default, semaphores behave like locks, letting only one thread <code>down()</code> them at a time. However, there are other uses for semaphores.</p>

<p>Each semaphore has a counter attached to it. By default, semaphores are created with the counter set to one, <code>down()</code> decrements the counter by one, and <code>up()</code> increments by one. However, we can override any or all of these defaults simply by passing in different values:</p>

<pre><code>use threads;
use Thread::Semaphore;

my $semaphore = Thread::Semaphore-&gt;new(5);
                # Creates a semaphore with the counter set to five

my $thr1 = threads-&gt;create(\&amp;sub1);
my $thr2 = threads-&gt;create(\&amp;sub1);

sub sub1 {
    $semaphore-&gt;down(5); # Decrements the counter by five
    # Do stuff here
    $semaphore-&gt;up(5); # Increment the counter by five
}

$thr1-&gt;detach();
$thr2-&gt;detach();</code></pre>

<p>If <code>down()</code> attempts to decrement the counter below zero, it blocks until the counter is large enough. Note that while a semaphore can be created with a starting count of zero, any <code>up()</code> or <code>down()</code> always changes the counter by at least one, and so <code>$semaphore-&gt;down(0)</code> is the same as <code>$semaphore-&gt;down(1)</code>.</p>

<p>The question, of course, is why would you do something like this? Why create a semaphore with a starting count that&#39;s not one, or why decrement or increment it by more than one? The answer is resource availability. Many resources that you want to manage access for can be safely used by more than one thread at once.</p>

<p>For example, let&#39;s take a GUI driven program. It has a semaphore that it uses to synchronize access to the display, so only one thread is ever drawing at once. Handy, but of course you don&#39;t want any thread to start drawing until things are properly set up. In this case, you can create a semaphore with a counter set to zero, and up it when things are ready for drawing.</p>

<p>Semaphores with counters greater than one are also useful for establishing quotas. Say, for example, that you have a number of threads that can do I/O at once. You don&#39;t want all the threads reading or writing at once though, since that can potentially swamp your I/O channels, or deplete your process&#39;s quota of filehandles. You can use a semaphore initialized to the number of concurrent I/O requests (or open files) that you want at any one time, and have your threads quietly block and unblock themselves.</p>

<p>Larger increments or decrements are handy in those cases where a thread needs to check out or return a number of resources at once.</p>

<h2 id="Waiting-for-a-Condition"><a class="permalink" href="perlthrtut.html#Waiting-for-a-Condition">#</a><a id="Waiting1"></a>Waiting for a Condition</h2>

<p>The functions <code>cond_wait()</code> and <code>cond_signal()</code> can be used in conjunction with locks to notify co-operating threads that a resource has become available. They are very similar in use to the functions found in <code>pthreads</code>. However for most purposes, queues are simpler to use and more intuitive. See <a href="./threads::shared.html">threads::shared</a> for more details.</p>

<h2 id="Giving-up-control"><a class="permalink" href="perlthrtut.html#Giving-up-control">#</a><a id="Giving"></a>Giving up control</h2>

<p>There are times when you may find it useful to have a thread explicitly give up the CPU to another thread. You may be doing something processor-intensive and want to make sure that the user-interface thread gets called frequently. Regardless, there are times that you might want a thread to give up the processor.</p>

<p>Perl&#39;s threading package provides the <code>yield()</code> function that does this. <code>yield()</code> is pretty straightforward, and works like this:</p>

<pre><code>use threads;

sub loop {
    my $thread = shift;
    my $foo = 50;
    while($foo--) { print(&quot;In thread $thread\n&quot;); }
    threads-&gt;yield();
    $foo = 50;
    while($foo--) { print(&quot;In thread $thread\n&quot;); }
}

my $thr1 = threads-&gt;create(\&amp;loop, &#39;first&#39;);
my $thr2 = threads-&gt;create(\&amp;loop, &#39;second&#39;);
my $thr3 = threads-&gt;create(\&amp;loop, &#39;third&#39;);</code></pre>

<p>It is important to remember that <code>yield()</code> is only a hint to give up the CPU, it depends on your hardware, OS and threading libraries what actually happens. <b>On many operating systems, yield() is a no-op.</b> Therefore it is important to note that one should not build the scheduling of the threads around <code>yield()</code> calls. It might work on your platform but it won&#39;t work on another platform.</p>

<h1 id="General-Thread-Utility-Routines"><a class="permalink" href="perlthrtut.html#General-Thread-Utility-Routines">#</a><a id="General"></a>General Thread Utility Routines</h1>

<p>We&#39;ve covered the workhorse parts of Perl&#39;s threading package, and with these tools you should be well on your way to writing threaded code and packages. There are a few useful little pieces that didn&#39;t really fit in anyplace else.</p>

<h2 id="What-Thread-Am-I-In?"><a class="permalink" href="perlthrtut.html#What-Thread-Am-I-In?">#</a><a id="What2"></a><a id="What-Thread-Am-I-In"></a>What Thread Am I In?</h2>

<p>The <code>threads-&gt;self()</code> class method provides your program with a way to get an object representing the thread it&#39;s currently in. You can use this object in the same way as the ones returned from thread creation.</p>

<h2 id="Thread-IDs"><a class="permalink" href="perlthrtut.html#Thread-IDs">#</a><a id="Thread3"></a>Thread IDs</h2>

<p><code>tid()</code> is a thread object method that returns the thread ID of the thread the object represents. Thread IDs are integers, with the main thread in a program being 0. Currently Perl assigns a unique TID to every thread ever created in your program, assigning the first thread to be created a TID of 1, and increasing the TID by 1 for each new thread that&#39;s created. When used as a class method, <code>threads-&gt;tid()</code> can be used by a thread to get its own TID.</p>

<h2 id="Are-These-Threads-The-Same?"><a class="permalink" href="perlthrtut.html#Are-These-Threads-The-Same?">#</a><a id="Are"></a><a id="Are-These-Threads-The-Same"></a>Are These Threads The Same?</h2>

<p>The <code>equal()</code> method takes two thread objects and returns true if the objects represent the same thread, and false if they don&#39;t.</p>

<p>Thread objects also have an overloaded <code>==</code> comparison so that you can do comparison on them as you would with normal objects.</p>

<h2 id="What-Threads-Are-Running?"><a class="permalink" href="perlthrtut.html#What-Threads-Are-Running?">#</a><a id="What3"></a><a id="What-Threads-Are-Running"></a>What Threads Are Running?</h2>

<p><code>threads-&gt;list()</code> returns a list of thread objects, one for each thread that&#39;s currently running and not detached. Handy for a number of things, including cleaning up at the end of your program (from the main Perl thread, of course):</p>

<pre><code># Loop through all the threads
foreach my $thr (threads-&gt;list()) {
    $thr-&gt;join();
}</code></pre>

<p>If some threads have not finished running when the main Perl thread ends, Perl will warn you about it and die, since it is impossible for Perl to clean up itself while other threads are running.</p>

<p>NOTE: The main Perl thread (thread 0) is in a <i>detached</i> state, and so does not appear in the list returned by <code>threads-&gt;list()</code>.</p>

<h1 id="A-Complete-Example"><a class="permalink" href="perlthrtut.html#A-Complete-Example">#</a><a id="A2"></a>A Complete Example</h1>

<p>Confused yet? It&#39;s time for an example program to show some of the things we&#39;ve covered. This program finds prime numbers using threads.</p>

<pre><code> 1 #!/usr/bin/perl
 2 # prime-pthread, courtesy of Tom Christiansen
 3
 4 use strict;
 5 use warnings;
 6
 7 use threads;
 8 use Thread::Queue;
 9
10 sub check_num {
11     my ($upstream, $cur_prime) = @_;
12     my $kid;
13     my $downstream = Thread::Queue-&gt;new();
14     while (my $num = $upstream-&gt;dequeue()) {
15         next unless ($num % $cur_prime);
16         if ($kid) {
17             $downstream-&gt;enqueue($num);
18         } else {
19             print(&quot;Found prime: $num\n&quot;);
20             $kid = threads-&gt;create(\&amp;check_num, $downstream, $num);
21             if (! $kid) {
22                 warn(&quot;Sorry.  Ran out of threads.\n&quot;);
23                 last;
24             }
25         }
26     }
27     if ($kid) {
28         $downstream-&gt;enqueue(undef);
29         $kid-&gt;join();
30     }
31 }
32
33 my $stream = Thread::Queue-&gt;new(3..1000, undef);
34 check_num($stream, 2);</code></pre>

<p>This program uses the pipeline model to generate prime numbers. Each thread in the pipeline has an input queue that feeds numbers to be checked, a prime number that it&#39;s responsible for, and an output queue into which it funnels numbers that have failed the check. If the thread has a number that&#39;s failed its check and there&#39;s no child thread, then the thread must have found a new prime number. In that case, a new child thread is created for that prime and stuck on the end of the pipeline.</p>

<p>This probably sounds a bit more confusing than it really is, so let&#39;s go through this program piece by piece and see what it does. (For those of you who might be trying to remember exactly what a prime number is, it&#39;s a number that&#39;s only evenly divisible by itself and 1.)</p>

<p>The bulk of the work is done by the <code>check_num()</code> subroutine, which takes a reference to its input queue and a prime number that it&#39;s responsible for. After pulling in the input queue and the prime that the subroutine is checking (line 11), we create a new queue (line 13) and reserve a scalar for the thread that we&#39;re likely to create later (line 12).</p>

<p>The while loop from line 14 to line 26 grabs a scalar off the input queue and checks against the prime this thread is responsible for. Line 15 checks to see if there&#39;s a remainder when we divide the number to be checked by our prime. If there is one, the number must not be evenly divisible by our prime, so we need to either pass it on to the next thread if we&#39;ve created one (line 17) or create a new thread if we haven&#39;t.</p>

<p>The new thread creation is line 20. We pass on to it a reference to the queue we&#39;ve created, and the prime number we&#39;ve found. In lines 21 through 24, we check to make sure that our new thread got created, and if not, we stop checking any remaining numbers in the queue.</p>

<p>Finally, once the loop terminates (because we got a 0 or <code>undef</code> in the queue, which serves as a note to terminate), we pass on the notice to our child, and wait for it to exit if we&#39;ve created a child (lines 27 and 30).</p>

<p>Meanwhile, back in the main thread, we first create a queue (line 33) and queue up all the numbers from 3 to 1000 for checking, plus a termination notice. Then all we have to do to get the ball rolling is pass the queue and the first prime to the <code>check_num()</code> subroutine (line 34).</p>

<p>That&#39;s how it works. It&#39;s pretty simple; as with many Perl programs, the explanation is much longer than the program.</p>

<h1 id="Different-implementations-of-threads"><a class="permalink" href="perlthrtut.html#Different-implementations-of-threads">#</a><a id="Different"></a>Different implementations of threads</h1>

<p>Some background on thread implementations from the operating system viewpoint. There are three basic categories of threads: user-mode threads, kernel threads, and multiprocessor kernel threads.</p>

<p>User-mode threads are threads that live entirely within a program and its libraries. In this model, the OS knows nothing about threads. As far as it&#39;s concerned, your process is just a process.</p>

<p>This is the easiest way to implement threads, and the way most OSes start. The big disadvantage is that, since the OS knows nothing about threads, if one thread blocks they all do. Typical blocking activities include most system calls, most I/O, and things like <code>sleep()</code>.</p>

<p>Kernel threads are the next step in thread evolution. The OS knows about kernel threads, and makes allowances for them. The main difference between a kernel thread and a user-mode thread is blocking. With kernel threads, things that block a single thread don&#39;t block other threads. This is not the case with user-mode threads, where the kernel blocks at the process level and not the thread level.</p>

<p>This is a big step forward, and can give a threaded program quite a performance boost over non-threaded programs. Threads that block performing I/O, for example, won&#39;t block threads that are doing other things. Each process still has only one thread running at once, though, regardless of how many CPUs a system might have.</p>

<p>Since kernel threading can interrupt a thread at any time, they will uncover some of the implicit locking assumptions you may make in your program. For example, something as simple as <code>$x = $x + 2</code> can behave unpredictably with kernel threads if <code>$x</code> is visible to other threads, as another thread may have changed <code>$x</code> between the time it was fetched on the right hand side and the time the new value is stored.</p>

<p>Multiprocessor kernel threads are the final step in thread support. With multiprocessor kernel threads on a machine with multiple CPUs, the OS may schedule two or more threads to run simultaneously on different CPUs.</p>

<p>This can give a serious performance boost to your threaded program, since more than one thread will be executing at the same time. As a tradeoff, though, any of those nagging synchronization issues that might not have shown with basic kernel threads will appear with a vengeance.</p>

<p>In addition to the different levels of OS involvement in threads, different OSes (and different thread implementations for a particular OS) allocate CPU cycles to threads in different ways.</p>

<p>Cooperative multitasking systems have running threads give up control if one of two things happen. If a thread calls a yield function, it gives up control. It also gives up control if the thread does something that would cause it to block, such as perform I/O. In a cooperative multitasking implementation, one thread can starve all the others for CPU time if it so chooses.</p>

<p>Preemptive multitasking systems interrupt threads at regular intervals while the system decides which thread should run next. In a preemptive multitasking system, one thread usually won&#39;t monopolize the CPU.</p>

<p>On some systems, there can be cooperative and preemptive threads running simultaneously. (Threads running with realtime priorities often behave cooperatively, for example, while threads running at normal priorities behave preemptively.)</p>

<p>Most modern operating systems support preemptive multitasking nowadays.</p>

<h1 id="Performance-considerations"><a class="permalink" href="perlthrtut.html#Performance-considerations">#</a><a id="Performance"></a>Performance considerations</h1>

<p>The main thing to bear in mind when comparing Perl&#39;s <i>ithreads</i> to other threading models is the fact that for each new thread created, a complete copy of all the variables and data of the parent thread has to be taken. Thus, thread creation can be quite expensive, both in terms of memory usage and time spent in creation. The ideal way to reduce these costs is to have a relatively short number of long-lived threads, all created fairly early on (before the base thread has accumulated too much data). Of course, this may not always be possible, so compromises have to be made. However, after a thread has been created, its performance and extra memory usage should be little different than ordinary code.</p>

<p>Also note that under the current implementation, shared variables use a little more memory and are a little slower than ordinary variables.</p>

<h1 id="Process-scope-Changes"><a class="permalink" href="perlthrtut.html#Process-scope-Changes">#</a><a id="Process1"></a>Process-scope Changes</h1>

<p>Note that while threads themselves are separate execution threads and Perl data is thread-private unless explicitly shared, the threads can affect process-scope state, affecting all the threads.</p>

<p>The most common example of this is changing the current working directory using <code>chdir()</code>. One thread calls <code>chdir()</code>, and the working directory of all the threads changes.</p>

<p>Even more drastic example of a process-scope change is <code>chroot()</code>: the root directory of all the threads changes, and no thread can undo it (as opposed to <code>chdir()</code>).</p>

<p>Further examples of process-scope changes include <code>umask()</code> and changing uids and gids.</p>

<p>Thinking of mixing <code>fork()</code> and threads? Please lie down and wait until the feeling passes. Be aware that the semantics of <code>fork()</code> vary between platforms. For example, some Unix systems copy all the current threads into the child process, while others only copy the thread that called <code>fork()</code>. You have been warned!</p>

<p>Similarly, mixing signals and threads may be problematic. Implementations are platform-dependent, and even the POSIX semantics may not be what you expect (and Perl doesn&#39;t even give you the full POSIX API). For example, there is no way to guarantee that a signal sent to a multi-threaded Perl application will get intercepted by any particular thread. (However, a recently added feature does provide the capability to send signals between threads. See <a href="threads.html#THREAD-SIGNALLING">&quot;THREAD SIGNALLING&quot; in threads</a> for more details.)</p>

<h1 id="Thread-Safety-of-System-Libraries"><a class="permalink" href="perlthrtut.html#Thread-Safety-of-System-Libraries">#</a><a id="Thread4"></a>Thread-Safety of System Libraries</h1>

<p>Whether various library calls are thread-safe is outside the control of Perl. Calls often suffering from not being thread-safe include: <code>localtime()</code>, <code>gmtime()</code>, functions fetching user, group and network information (such as <code>getgrent()</code>, <code>gethostent()</code>, <code>getnetent()</code> and so on), <code>readdir()</code>, <code>rand()</code>, and <code>srand()</code>. In general, calls that depend on some global external state.</p>

<p>If the system Perl is compiled in has thread-safe variants of such calls, they will be used. Beyond that, Perl is at the mercy of the thread-safety or -unsafety of the calls. Please consult your C library call documentation.</p>

<p>On some platforms the thread-safe library interfaces may fail if the result buffer is too small (for example the user group databases may be rather large, and the reentrant interfaces may have to carry around a full snapshot of those databases). Perl will start with a small buffer, but keep retrying and growing the result buffer until the result fits. If this limitless growing sounds bad for security or memory consumption reasons you can recompile Perl with <code>PERL_REENTRANT_MAXSIZE</code> defined to the maximum number of bytes you will allow.</p>

<h1 id="Conclusion"><a class="permalink" href="perlthrtut.html#Conclusion">#</a>Conclusion</h1>

<p>A complete thread tutorial could fill a book (and has, many times), but with what we&#39;ve covered in this introduction, you should be well on your way to becoming a threaded Perl expert.</p>

<h1 id="SEE-ALSO"><a class="permalink" href="perlthrtut.html#SEE-ALSO">#</a><a id="SEE"></a>SEE ALSO</h1>

<p>Annotated POD for <a href="threads.html">threads</a>: <a href="https://web.archive.org/web/20171028020148/http://annocpan.org/?mode=search&amp;field=Module&amp;name=threads">https://web.archive.org/web/20171028020148/http://annocpan.org/?mode=search&amp;field=Module&amp;name=threads</a></p>

<p>Latest version of <a href="threads.html">threads</a> on CPAN: <a href="https://metacpan.org/pod/threads">https://metacpan.org/pod/threads</a></p>

<p>Annotated POD for <a href="./threads::shared.html">threads::shared</a>: <a href="https://web.archive.org/web/20171028020148/http://annocpan.org/?mode=search&amp;field=Module&amp;name=threads%3A%3Ashared">https://web.archive.org/web/20171028020148/http://annocpan.org/?mode=search&amp;field=Module&amp;name=threads%3A%3Ashared</a></p>

<p>Latest version of <a href="./threads::shared.html">threads::shared</a> on CPAN: <a href="https://metacpan.org/pod/threads::shared">https://metacpan.org/pod/threads::shared</a></p>

<p>Perl threads mailing list: <a href="https://lists.perl.org/list/ithreads.html">https://lists.perl.org/list/ithreads.html</a></p>

<h1 id="Bibliography"><a class="permalink" href="perlthrtut.html#Bibliography">#</a>Bibliography</h1>

<p>Here&#39;s a short bibliography courtesy of Jürgen Christoffel:</p>

<h2 id="Introductory-Texts"><a class="permalink" href="perlthrtut.html#Introductory-Texts">#</a><a id="Introductory"></a>Introductory Texts</h2>

<p>Birrell, Andrew D. An Introduction to Programming with Threads. Digital Equipment Corporation, 1989, DEC-SRC Research Report #35 online as <a href="https://www.hpl.hp.com/techreports/Compaq-DEC/SRC-RR-35.pdf">https://www.hpl.hp.com/techreports/Compaq-DEC/SRC-RR-35.pdf</a> (highly recommended)</p>

<p>Robbins, Kay. A., and Steven Robbins. Practical Unix Programming: A Guide to Concurrency, Communication, and Multithreading. Prentice-Hall, 1996.</p>

<p>Lewis, Bill, and Daniel J. Berg. Multithreaded Programming with Pthreads. Prentice Hall, 1997, ISBN 0-13-443698-9 (a well-written introduction to threads).</p>

<p>Nelson, Greg (editor). Systems Programming with Modula-3. Prentice Hall, 1991, ISBN 0-13-590464-1.</p>

<p>Nichols, Bradford, Dick Buttlar, and Jacqueline Proulx Farrell. Pthreads Programming. O&#39;Reilly &amp; Associates, 1996, ISBN 156592-115-1 (covers POSIX threads).</p>

<h2 id="OS-Related-References"><a class="permalink" href="perlthrtut.html#OS-Related-References">#</a><a id="OS"></a>OS-Related References</h2>

<p>Boykin, Joseph, David Kirschen, Alan Langerman, and Susan LoVerso. Programming under Mach. Addison-Wesley, 1994, ISBN 0-201-52739-1.</p>

<p>Tanenbaum, Andrew S. Distributed Operating Systems. Prentice Hall, 1995, ISBN 0-13-219908-4 (great textbook).</p>

<p>Silberschatz, Abraham, and Peter B. Galvin. Operating System Concepts, 4th ed. Addison-Wesley, 1995, ISBN 0-201-59292-4</p>

<h2 id="Other-References"><a class="permalink" href="perlthrtut.html#Other-References">#</a><a id="Other"></a>Other References</h2>

<p>Arnold, Ken and James Gosling. The Java Programming Language, 2nd ed. Addison-Wesley, 1998, ISBN 0-201-31006-6.</p>

<p>comp.programming.threads FAQ, <a href="http://www.serpentine.com/~bos/threads-faq/">http://www.serpentine.com/~bos/threads-faq/</a></p>

<p>Le Sergent, T. and B. Berthomieu. &quot;Incremental MultiThreaded Garbage Collection on Virtually Shared Memory Architectures&quot; in Memory Management: Proc. of the International Workshop IWMM 92, St. Malo, France, September 1992, Yves Bekkers and Jacques Cohen, eds. Springer, 1992, ISBN 3540-55940-X (real-life thread applications).</p>

<p>Artur Bergman, &quot;Where Wizards Fear To Tread&quot;, June 11, 2002, <a href="http://www.perl.com/pub/a/2002/06/11/threads.html">http://www.perl.com/pub/a/2002/06/11/threads.html</a></p>

<h1 id="Acknowledgements"><a class="permalink" href="perlthrtut.html#Acknowledgements">#</a>Acknowledgements</h1>

<p>Thanks (in no particular order) to Chaim Frenkel, Steve Fink, Gurusamy Sarathy, Ilya Zakharevich, Benjamin Sugars, Jürgen Christoffel, Joshua Pritikin, and Alan Burlison, for their help in reality-checking and polishing this article. Big thanks to Tom Christiansen for his rewrite of the prime number generator.</p>

<h1 id="AUTHOR"><a class="permalink" href="perlthrtut.html#AUTHOR">#</a>AUTHOR</h1>

<p>Dan Sugalski &lt;dan@sidhe.org&gt;</p>

<p>Slightly modified by Arthur Bergman to fit the new thread model/module.</p>

<p>Reworked slightly by Jörg Walter &lt;jwalt@cpan.org&gt; to be more concise about thread-safety of Perl code.</p>

<p>Rearranged slightly by Elizabeth Mattijsen &lt;liz@dijkmat.nl&gt; to put less emphasis on yield().</p>

<h1 id="Copyrights"><a class="permalink" href="perlthrtut.html#Copyrights">#</a>Copyrights</h1>

<p>The original version of this article originally appeared in The Perl Journal #10, and is copyright 1998 The Perl Journal. It appears courtesy of Jon Orwant and The Perl Journal. This document may be distributed under the same terms as Perl itself.</p>


      </div>
      <div id="footer">
        <p>Perldoc Browser is maintained by Dan Book (<a href="https://metacpan.org/author/DBOOK">DBOOK</a>). Please contact him via the <a href="https://github.com/Grinnz/perldoc-browser/issues">GitHub issue tracker</a> or <a href="mailto:dbook@cpan.org">email</a> regarding any issues with the site itself, search, or rendering of documentation.</p>

<p>The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please contact them via the <a href="https://github.com/Perl/perl5/issues">Perl issue tracker</a>, the <a href="https://lists.perl.org/list/perl5-porters.html">mailing list</a>, or <a href="https://kiwiirc.com/client/irc.perl.org/p5p">IRC</a> to report any issues with the contents or format of the documentation.</p>


      </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.slim.min.js" integrity="sha512-/DXTXr6nQodMUiq+IUJYCt2PPOUjrHJ9wFrqpJ3XkgPNOZVfMok7cRw6CSxyCQxXn6ozlESsSh1/sMCTF1rL/g==" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js" integrity="sha512-ubuT8Z88WxezgSqf3RLuNi5lmjstiJcyezx34yIU2gAHonIi27Na7atqzUZCOoY4CExaoFumzOsFQ2Ch+I/HCw==" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
    <script src="../highlight.pack.js"></script>
    <script>hljs.highlightAll();</script>
  </body>
</html>
